const express = require('express');
const router = express.Router();
const Service = require('../model/Service');
const { User } = require('../model/model'); // 使用正确的用户模型导入
const Appointment = require('../model/Appointment');

// 获取所有可用服务项目
router.get('/services', async (req, res) => {
    try {
        const services = await Service.find({ status: true })
            .select('name category price duration description image')
            .sort({ createTime: -1 });

        res.json({
            code: 200,
            message: '获取服务列表成功',
            data: services
        });
    } catch (error) {
        console.error('获取服务列表失败:', error);
        res.status(500).json({
            code: 500,
            message: '获取服务列表失败',
            error: error.message
        });
    }
});

// 根据id获取服务项目
router.get('/services/:id', async (req, res) => {
    try {
        const { id } = req.params;
        const service = await Service.findById(id)
            .select('name category price duration description image');

        if (!service) {
            return res.status(404).json({
                code: 404,
                message: '服务项目不存在'
            });
        }

        res.json({
            code: 200,
            message: '获取服务项目成功',
            data: service
        });
    } catch (error) {
        console.error('获取服务项目失败:', error);
        res.status(500).json({
            code: 500,
            message: '获取服务项目失败',
            error: error.message
        });
    }
})

// 根据服务类型获取技师列表
router.get('/technicians', async (req, res) => {
    try {
        const { serviceCategory, date } = req.query;

        // 查询role为689dc4e6889e4412b3bdfed2的用户（技师）
        let query = {
            role: '689dc4e6889e4412b3bdfed2',
            status: true
        };

        // 如果指定了服务类型，筛选有相关技能的技师
        if (serviceCategory) {
            // 这里可以根据实际需求添加技能筛选逻辑
            // 暂时返回所有技师，后续可以根据用户表中的技能字段进行筛选
        }

        // 如果指定了日期，检查技师的工作安排
        if (date) {
            const appointmentDate = new Date(date);
            const dayOfWeek = appointmentDate.getDay();
            // 这里可以根据实际需求添加工作日筛选逻辑
        }

        const technicians = await User.find(query)
            .select('username email phone sex age createTime')
            .sort({ createTime: -1 });

        // 为技师添加默认的技师信息
        const techniciansWithInfo = technicians.map(tech => ({
            _id: tech._id,
            name: tech.username, // 使用username作为技师姓名
            avatar: tech.username.charAt(0), // 使用用户名首字母作为头像
            rating: 4.5 + Math.random() * 0.5, // 随机评分4.5-5.0
            totalRatings: Math.floor(Math.random() * 100) + 50, // 随机评分次数
            status: '空闲中', // 默认状态
            skills: ['面部护理', '身体按摩', '足疗'], // 默认技能
            experience: Math.floor(Math.random() * 5) + 1, // 随机工作经验1-5年
            phone: tech.phone || '',
            email: tech.email || '',
            workSchedule: {
                startTime: '09:00',
                endTime: '18:00',
                workDays: [1, 2, 3, 4, 5, 6]
            }
        }));

        res.json({
            code: 200,
            message: '获取技师列表成功',
            data: techniciansWithInfo
        });
    } catch (error) {
        console.error('获取技师列表失败:', error);
        res.status(500).json({
            code: 500,
            message: '获取技师列表失败',
            error: error.message
        });
    }
});

// 检查技师在指定时间是否可用
router.get('/technician/availability', async (req, res) => {
    try {
        const { technicianId, date, time } = req.query;

        if (!technicianId || !date || !time) {
            return res.status(400).json({
                code: 400,
                message: '缺少必要参数'
            });
        }

        // 解析时间段
        const [startTime, endTime] = time.split('-');
        const appointmentDate = new Date(date);

        // 检查技师是否有冲突的预约
        const conflictingAppointments = await Appointment.find({
            technicianId,
            appointmentDate,
            status: { $in: ['待确认', '已确认', '服务中'] },
            $or: [
                {
                    appointmentTime: {
                        $regex: new RegExp(`^${startTime}|${endTime}`)
                    }
                },
                {
                    appointmentTime: {
                        $regex: new RegExp(`-${startTime}|-${endTime}`)
                    }
                }
            ]
        });

        const isAvailable = conflictingAppointments.length === 0;

        res.json({
            code: 200,
            message: '检查技师可用性成功',
            data: {
                isAvailable,
                conflictingAppointments: conflictingAppointments.length
            }
        });
    } catch (error) {
        console.error('检查技师可用性失败:', error);
        res.status(500).json({
            code: 500,
            message: '检查技师可用性失败',
            error: error.message
        });
    }
});

// 创建预约登记
router.post('/appointment', async (req, res) => {
    try {
        const {
            customerName,
            customerPhone,
            customerEmail,
            serviceId,
            technicianId,
            appointmentDate,
            appointmentTime,
            notes
        } = req.body;

        // 验证必要字段
        if (!customerName || !customerPhone || !serviceId || !technicianId || !appointmentDate || !appointmentTime) {
            return res.status(400).json({
                code: 400,
                message: '缺少必要字段'
            });
        }

        // 获取服务信息
        const service = await Service.findById(serviceId);
        if (!service) {
            return res.status(404).json({
                code: 404,
                message: '服务项目不存在'
            });
        }

        // 获取技师信息
        const technician = await User.findById(technicianId);
        if (!technician) {
            return res.status(404).json({
                code: 404,
                message: '技师不存在'
            });
        }

        // 检查技师在指定时间是否可用
        const [startTime] = appointmentTime.split('-');
        const conflictingAppointments = await Appointment.find({
            technicianId,
            appointmentDate,
            status: { $in: ['待确认', '已确认', '服务中'] },
            appointmentTime: {
                $regex: new RegExp(`^${startTime}|-${startTime}`)
            }
        });

        if (conflictingAppointments.length > 0) {
            return res.status(409).json({
                code: 409,
                message: '技师在该时间段已有预约'
            });
        }

        // 创建预约
        const appointment = new Appointment({
            customerName,
            customerPhone,
            customerEmail,
            serviceId,
            serviceName: service.name,
            servicePrice: service.price,
            serviceDuration: service.duration,
            technicianId,
            technicianName: technician.username, // 使用username作为技师姓名
            appointmentDate,
            appointmentTime,
            notes
        });

        await appointment.save();

        res.json({
            code: 200,
            message: '预约创建成功',
            data: {
                appointmentId: appointment._id,
                appointmentNumber: `AP${Date.now()}`
            }
        });
    } catch (error) {
        console.error('创建预约失败:', error);
        res.status(500).json({
            code: 500,
            message: '创建预约失败',
            error: error.message
        });
    }
});

// 获取预约详情
router.get('/appointment/:id', async (req, res) => {
    try {
        const appointment = await Appointment.findById(req.params.id)
            .populate('serviceId', 'name category price duration')
            .populate('technicianId', 'username email phone');

        if (!appointment) {
            return res.status(404).json({
                code: 404,
                message: '预约不存在'
            });
        }

        res.json({
            code: 200,
            message: '获取预约详情成功',
            data: appointment
        });
    } catch (error) {
        console.error('获取预约详情失败:', error);
        res.status(500).json({
            code: 500,
            message: '获取预约详情失败',
            error: error.message
        });
    }
});

// 更新预约状态
router.put('/appointment/:id/status', async (req, res) => {
    try {
        const { status, notes } = req.body;

        const appointment = await Appointment.findByIdAndUpdate(
            req.params.id,
            {
                status,
                notes: notes || undefined,
                updateTime: new Date()
            },
            { new: true }
        );

        if (!appointment) {
            return res.status(404).json({
                code: 404,
                message: '预约不存在'
            });
        }

        res.json({
            code: 200,
            message: '更新预约状态成功',
            data: appointment
        });
    } catch (error) {
        console.error('更新预约状态失败:', error);
        res.status(500).json({
            code: 500,
            message: '更新预约状态失败',
            error: error.message
        });
    }
});

// 取消预约
router.put('/appointment/:id/cancel', async (req, res) => {
    try {
        const { cancelReason } = req.body;

        const appointment = await Appointment.findByIdAndUpdate(
            req.params.id,
            {
                status: '已取消',
                cancelReason,
                cancelTime: new Date(),
                updateTime: new Date()
            },
            { new: true }
        );

        if (!appointment) {
            return res.status(404).json({
                code: 404,
                message: '预约不存在'
            });
        }

        res.json({
            code: 200,
            message: '预约取消成功',
            data: appointment
        });
    } catch (error) {
        console.error('取消预约失败:', error);
        res.status(500).json({
            code: 500,
            message: '取消预约失败',
            error: error.message
        });
    }
});

module.exports = router; 